/**
 * ReportGear(2011)
 */
package net.abbp.report.model.cell.style.background;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.util.Map;
import java.util.WeakHashMap;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import net.abbp.core.api.ICloneable;
import net.abbp.core.transform.xml.jaxb.ColorAdapter;

import com.reportgear.report.view.grid.util.GraphHelper;

/**
 * 颜色背景
 * 
 * @version 1.0 2011-3-18
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Color")
public class ColorBackground extends AbstractBackground implements ICloneable<ColorBackground> {
    private static Map<Color, ColorBackground> initializeCBG = new WeakHashMap<Color, ColorBackground>();
    @XmlJavaTypeAdapter(value = ColorAdapter.class)
    private Color color = null;

    public static ColorBackground getInstance() {
        return getInstance(null);
    }

    public static ColorBackground getInstance(Color color) {
        ColorBackground ground = initializeCBG.get(color);
        if (ground != null) {
            return ground;
        }

        ColorBackground background = new ColorBackground(color);

        initializeCBG.put(color, background);

        return background;
    }

    private ColorBackground() {
    }

    private ColorBackground(Color color) {
        this.color = color;
    }

    public Color getColor() {
        return this.color;
    }

    @Override
    public void paint(Graphics g, Shape shape) {
        Color color = getColor();

        if (color == null) {
            return;
        }

        Graphics2D g2 = (Graphics2D) g;
        Paint oldPaint = g2.getPaint();

        g2.setPaint(color);

        GraphHelper.fill(g2, shape);

        g2.setPaint(oldPaint);
    }

    @Override
    public ColorBackground clone() {
        return this;
    }
}